﻿using Jint;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using T.FAS.Runtime.Base.Entity;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using T.FAS.Runtime.Expression.Entity;
using T.FAS.Runtime.Expression.Service;
using System.Dynamic;
using T.FAS.Runtime.Expression.Plugin;

namespace T.FAS.Runtime.Expression.UnitTest
{
    [TestClass]
    public class CDOUnit
    {
        /// <summary>
        /// NewInstance
        /// </summary>
        [TestMethod]
        public void ExecuteNewInstance()
        {
            Dictionary<string, object> dic = new Dictionary<string, object>(); 
            var expr = "var record = {};";
            expr += $@"
            record.ActionID = null;
            record.ActionCode = null;
            record.ActionName = null;
            record.Code = '1';
            record.Name = '2';
            record.Creator = '';
            record.CreateTime = '';
            record.LastModifier = '';
            record.LastModifierName = '';
            record.LastModifyTime = '';
            return CDO.NewInstance('CDO_DO_TemplateV2',JSON.stringify(record)).Record";
            ExprResult exprResult = ExprService.GetInstance.JSExecute(expr, dic);
            Assert.IsTrue(exprResult.Result is TRecord);
        }
        /// <summary>
        /// Create Update Delete GetDataByID
        /// </summary>
        [TestMethod]
        public void ExecuteCDO()
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            string ID = Guid.NewGuid().ToString();
            var expr = "var record = {};";
            expr += $@"
            record.ID = '{ID}';
            record.Code = '1';
            record.Name = '2';
            record.Creator = '';
            record.CreateTime = '';
            record.LastModifier = '';
            record.LastModifierName = '';
            record.LastModifyTime = '';
            return CDO.Create('CDO_DO_TemplateV2',JSON.stringify(record)).Record.ID";
            ExprResult exprResult = ExprService.GetInstance.JSExecute(expr, dic);
            Assert.IsTrue(exprResult.Result.ToString() == ID);

            expr = $"CDO.GetDataByID('CDO_DO_TemplateV2','{ID}').Record.ID";
            exprResult = ExprService.GetInstance.JSExecute(expr, dic);
            Assert.IsTrue(exprResult.Result.ToString() == ID);

            expr = $@"var record = CDO.GetDataByID('CDO_DO_TemplateV2','{ID}').Record;
            record.Code='33'
            return CDO.Update('CDO_DO_TemplateV2',record).Record.Code";
            exprResult = ExprService.GetInstance.JSExecute(expr, dic);
            Assert.IsTrue(exprResult.Result.ToString() == "33");

            expr = $"CDO.Delete('CDO_DO_TemplateV2','{ID}')";
            exprResult = ExprService.GetInstance.JSExecute(expr, dic);
            Assert.IsTrue(exprResult.State == ResultState.Success);

            expr = $"CDO.GetDataByID('CDO_DO_TemplateV2','{ID}').Record.ID";
            exprResult = ExprService.GetInstance.JSExecute(expr, dic);
            Assert.IsTrue(exprResult.Result == null);
        }
        /// <summary>
        /// GetDataByID
        /// </summary>
        [TestMethod]
        public void GetDataByID()
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            string ID = Guid.NewGuid().ToString();
            var expr = $"CDO.GetDataByID('CDO_DO_TemplateV2','{ID}').Record.ID";
            var exprResult = ExprService.GetInstance.JSExecute(expr, dic);
            Assert.IsTrue(exprResult.Result == null);
        }
        /// <summary>
        /// ChangeState
        /// </summary>
        [TestMethod]
        public void ExecuteChangeState()
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            ExprResult exprResult = ExprService.GetInstance.JSExecute("var CDOID =\"793ff754-eb8f-4edf-81ab-5cd3b3bd79bb\";" +
                "var EventKey =\"接收\";" +
                "var TRecord ={\"SDO_TDepartment_Code\":\"0\",\"ID\":\"a2bc2730-df44-4dc5-ab15-bc310bb4228e\",\"SDO_TDepartment_Name\":\"公共技术部\",\"Code\":\"20211130031155\",\"Name\":\"新增2\",\"Creator\":\"873A4ADD-A93C-4ECB-A2F6-E812A2F48CA2\",\"CreatorName\":\"user1\",\"CreateTime\":\"2021-11-30 11:12:45\",\"LastModifier\":\"873A4ADD-A93C-4ECB-A2F6-E812A2F48CA2\",\"LastModifierName\":\"user1\",\"LastModifyTime\":{\"Value\":\"2021-11-30 00:00:00\",\"Data\":\"2021-11-30 00:00:00.000\",\"Format\":null},\"STATE\":1,\"SubDescription\":\"问题概述\",\"Description\":\"<p>描述</p>\",\"FDDepartment\":0,\"FDUser\":\"user1\",\"HopeDate\":\"2021-11-30 03:11:00\",\"PlanDate\":\"2021-11-30 03:11:00\",\"InitPlanDate\":\"2021-11-30 03:11:00\",\"ProjectID\":0,\"ProductLineID\":0,\"ApplicationID\":0,\"ModuleID\":0,\"FunctionID\":\"\",\"DutyDepartment\":null,\"DutyUser\":null,\"NextFlowType\":\"\",\"ProcessResultType\":\"\",\"ProcessInfo\":null};" +
                "CDO.ChangeState(CDOID,TRecord,EventKey)", dic);
            Assert.IsTrue(exprResult.State == ResultState.Fail);
        }
        /// <summary>
        /// FireEvent
        /// </summary>
        [TestMethod]
        public void ExecuteFireEvent()
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            ExprResult exprResult = ExprService.GetInstance.JSExecute("var SMID =\"793ff754-eb8f-4edf-81ab-5cd3b3bd79bb\";" +
                "var ColumnCode =\"STATE\";" +
                "var EventKey =\"接收\";" +
                "var TRecord ={\"SDO_TDepartment_Code\":\"0\",\"ID\":\"a2bc2730-df44-4dc5-ab15-bc310bb4228e\",\"SDO_TDepartment_Name\":\"公共技术部\",\"Code\":\"20211130031155\",\"Name\":\"新增2\",\"Creator\":\"873A4ADD-A93C-4ECB-A2F6-E812A2F48CA2\",\"CreatorName\":\"user1\",\"CreateTime\":\"2021-11-30 11:12:45\",\"LastModifier\":\"873A4ADD-A93C-4ECB-A2F6-E812A2F48CA2\",\"LastModifierName\":\"user1\",\"LastModifyTime\":{\"Value\":\"2021-11-30 00:00:00\",\"Data\":\"2021-11-30 00:00:00.000\",\"Format\":null},\"STATE\":1,\"SubDescription\":\"问题概述\",\"Description\":\"<p>描述</p>\",\"FDDepartment\":0,\"FDUser\":\"user1\",\"HopeDate\":\"2021-11-30 03:11:00\",\"PlanDate\":\"2021-11-30 03:11:00\",\"InitPlanDate\":\"2021-11-30 03:11:00\",\"ProjectID\":0,\"ProductLineID\":0,\"ApplicationID\":0,\"ModuleID\":0,\"FunctionID\":\"\",\"DutyDepartment\":null,\"DutyUser\":null,\"NextFlowType\":\"\",\"ProcessResultType\":\"\",\"ProcessInfo\":null};" +
                "CDO.FireEvent(SMID,ColumnCode,EventKey,TRecord)", dic);
            Assert.IsTrue(exprResult.State == ResultState.Fail);
        }
        /// <summary>
        /// 表达式执行
        /// </summary>
        [TestMethod]
        public void ExecuteExprBeginTransaction()
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            var expr = "var record = {};";
            expr += @"
            record.ID = '1234';
            record.Code = '1';
            record.Name = '2';
            var db = DB.GetDatabaseByConnectionKey('TTP.Database.TFAS.ConnectionString');
            var trans = db.BeginTransaction();
            try
            {
                CDO.Create(record);
                record.ID = '12345';
                Action.Create(record);
                trans.Commit();
            }
            catch(e)
            {
                trans.Rollback();
            }
            finally
            {
                trans.Dispose();
            }";
            ExprResult exprResult = ExprService.GetInstance.JSExecute(expr, dic);
            Assert.IsTrue(exprResult.State == ResultState.Success);
        }
        /// <summary>
        /// FasContext
        /// </summary>
        [TestMethod]
        public void ExecuteFasContext()
        {
            ChangeSet changeSet = new ChangeSet();
            changeSet.ChangeItems = new List<ChangeItem> { new ChangeItem { ItemCode = "Name", OldData = "OldData1", NewData = "NewData1" } };

            Dictionary<string, object> dic = new Dictionary<string, object>();
            dic.Add("changeSet", changeSet);
            ExprResult exprResult = ExprService.GetInstance.JSExecute("changeSet['Name'].OldData", dic);
            Assert.IsTrue(exprResult.State == ResultState.Fail);
        }

        [TestMethod]
        public void ExecuteDQ()
        {
            Dictionary<string, object> dic = new Dictionary<string, object>();
            var expr = @"let DefaultInputFilter='';
		let PageIndex='1';
		let PageSize='1000';
		let AdvancedFilter='';
		let AdvancedSort='';
		DataQuery.GetCDO_DO_projectbug0714BasicList(DefaultInputFilter,PageIndex,PageSize,AdvancedFilter,AdvancedSort).List";
             ExprService.GetInstance.DebugExecute(expr, dic);
          
        }
    }
}
